import HelperFunctions as HF
import numpy as np
from datetime import datetime
from time import strftime
import csv
import os

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def get_inputs():
    """Given the list of inputs for the script when run, return an object
    containing the variables for the script"""
    try:
        '''
        sInputFC = HF.pGP.GetParameterAsText(0)                     # Input Feature Class
        sZField = HF.pGP.GetParameterAsText(1).upper()              # Attribute Field Name
        sOutputFC = HF.pGP.GetParameterAsText(2)                    # Output Feature Class
        lsField = sZField.split(";")
        '''

        #This block can be used to test the code using provided datasets
        #sInputFC = "C:/_DATA/CancerData/test/Mar21/pvalue/16_4polygon/TP1000_16_4polygon.shp"
        sInputFC = "C:/_DATA/CancerData/SatScan/NortheeaternUS.shp"
        #contiguityFC = "C:/_DATA/CancerData/NCTrtCancer_ROOK.csv"
        #contiguityFC = "C:/_DATA/CancerData/test/Jan15/TP1000_1m_1000cancer.shp.ctg"
        sInputTreeCSV = 'C:/_DATA/CancerData/SatScan/NortheeaternUS_re_contiguity.csv'
        #sZField =  "Pop;Cancer;Density"
        sOutputFolder = "C:/temp/"
        #sOutputFC = "C:/temp/TP1000_1m_sharedborderlength.csv"
        sUniqueID = "FID"
 
    except: raise HF.ReportError (HF.msgParseErr)

    try:
        obj = HF.Gen()
        obj.add('sInputFC',sInputFC)
        obj.add('sOutputFolder',sOutputFolder)
        obj.add('sInputTreeCSV',sInputTreeCSV)
        #obj.add('sOutputFC', sOutputFC)
        obj.add('sUniqueID', sUniqueID)

    except: raise HF.ReportError (HF.msgInputsErr)

    return obj

def cal_point_xy():
    pRows = HF.pGP.SearchCursor(inputs.sInputFC)
    pRow = pRows.Next()

    iBadRecCnt = 0
    temp_xy = np.array([])
    while pRow <> None:
        feat = pRow.shape
        try:
            cent = feat.centroid.rsplit()
            dTemp = []
            dTemp.append(float(cent[0]))
            dTemp.append(float(cent[1]))
            temp_xy = np.append(temp_xy,dTemp)
        except:
            iBadRecCnt += 1   
        pRow = pRows.Next()
    #print type(cent)
    temp_xy.shape = (-1, 2)
    pRows = None           
    print iBadRecCnt, "error!"
    return temp_xy  

def delete_shapefiles(temp_path):
    # e.g. temp_path = "c:/temp/a.shp"    a.dbf, a.prj, a.sbn, a.sbx, a.shp, a.shp.xml, a.shx will be deleted
    temp_suffix = ["dbf", "prj", "sbn", "sbx", "shp", "shp.xml", "shx"]
    if os.path.exists(temp_path):
        for item in temp_suffix:
            if os.path.exists(temp_path[:-3] + item):
                os.remove(temp_path[:-3] + item)
    else:
        print temp_path + " does not exist!"
        return

def build_data_list(inputCSV):
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    temp_list = np.array([])
    i = 0
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        #unit_attri[i,4] = int(float(record[ra.fieldnames[-1]]))
        for name in ra.fieldnames:
            temp_list = np.append(temp_list, float(record[name]))
    temp_list.shape = (-1,len(ra.fieldnames))
    return temp_list

def output_line(outputName):
    #outputName = "nc_tree_0.shp"
    if os.path.exists(inputs.sOutputFolder + outputName):
        delete_shapefiles(inputs.sOutputFolder + outputName)
        
    HF.pGP.CreateFeatureclass(inputs.sOutputFolder, outputName, 'POLYLINE')
    pInsert = HF.pGP.InsertCursor(inputs.sOutputFolder + outputName)
    pnt = HF.pGP.createobject("Point")
    lineArray = HF.pGP.createobject("Array")
    #pRow = pRows.Next()
    i = 0
    for item in tree_edge:
        pnt.id = i
        pnt.x = point_xy[int(item[0]), 0]
        pnt.y = point_xy[int(item[0]), 1]
        lineArray.add(pnt)
        i += 1
        pnt.id = i
        pnt.x = point_xy[int(item[1]), 0]
        pnt.y = point_xy[int(item[1]), 1]
        lineArray.add(pnt)
        i += 1
        feat = pInsert.NewRow() 
        feat.shape = lineArray 
        pInsert.InsertRow(feat) 
        lineArray.RemoveAll() 
        
    
#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "===================="
    inputs = get_inputs()
    tree_edge = build_data_list(inputs.sInputTreeCSV)
    point_xy = cal_point_xy()
    outputName = "neUS_tree_0.shp"
    output_line(outputName)
    print "Done!"